package com.atguigu.gulimall.ssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author Yanglinfengkk
 * 单点登录服务器 登录操作
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 开发请求
     * @param token
     * @return
     */
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    /**
     * 客户端跳转链接
     * url  地址栏带的参数值
     *
     * @return
     */
    @GetMapping("/login.html")
    public String LoginPage(@RequestParam("redirect_url") String url,
                            Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            //sso_token不为空,说明之前有人登陆过,浏览器留下了痕迹
            return "redirect:" + url + "?token=" + sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 单点服务器进行登录操作
     * url  跳转过来地址栏参数值 隐藏域
     * username 用户名
     * password 密码
     * url      跳转回去的地址
     *
     * @return
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //TODO 逻辑代码...把登录成功的用户放在Redis
            //为每个用户发放令牌,唯一  username(数据库连接存用户)
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);

            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            //登录成功跳转?   跳回到之前的页面
            log.info("token:{}", uuid);
            return "redirect:" + url + "?token=" + uuid;
        }
        //登录失败.跳转登录页重新登录
        return "login";
    }

}
